# -*- coding: utf-8 -*-

from __future__ import with_statement

from w.settings import W
from datetime import datetime
import os

#translates domain dot notation to the domain name and locale directory. Algorithm
#is very simple: path.to.dir.name -> name as domain file name and path/to/dir
#as locale directory.
def parseDomain(domain):
    res = domain.replace('.','/').rsplit('/',1)
    return (res[1], res[0]) if len(res)>1 else (res[0], '')

class PoData(object):
    header = """
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\\n"
"Report-Msgid-Bugs-To: \\n"
"POT-Creation-Date: %s\\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n"
"Language-Team: LANGUAGE <LL@li.org>\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=%s\\n"
"Content-Transfer-Encoding: %s\\n"
"""
    def __init__(self,content=None, charset='UTF-8', cte='8bit'):
        self.header = self.header%(datetime.datetime.now(),charset,cte)
        self.content = content or {}

    def __str__(self):
        tmpl = 'msgid "%s"\nmsgstr "%s"\n\n'
        content = ''.join([tmpl%(n,v.strip()) for n,v in self.content.items()])
        return '%s\n%s'%(self.header, content)

    def loadContentFromLines(self, lineSeq):
        curID = ''

        for line in lineSeq:
            if line.startswith('#'):
                continue
            elif line.startswith('msgid'):
                curID = line[7:-2]
            elif line.startswith('msgstr') and curID:
                self.content[curID] = line[8:-2].strip()
            else:
                pass

class GettextProcessor(object):
    def filePath(self, domain, lang, type='po'):
        name,ldir = parseDomain(domain)
        return '%s/%s/%s/LC_MESSAGES/%s.%s'%(W.I18N.ROOT_DIR,ldir,lang,name,type)
        
    def readPoData(self, domain, lang):
        res = PoData()
        with file(self.filePath(domain, lang),'r') as f:
            res.loadContentFromLines(f.readlines())
        return res
        
    def writePoData(self, domain, lang, data):
        with file(self.filePath(domain, lang),'w') as f:
            f.write(str(data))
    
    def buildMoFile(self, domain, lang):
        command = 'msgfmt -o %s %s'%(self.filePath(domain, lang, 'mo'),
                                     self.filePath(domain, lang))
        os.system(command)

